import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectRequest;
import com.obs.services.model.PutObjectResult;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;

/**
 * @create: 2025-03-17 14:46
 * @author: kongbo
 * @description: 图片上传到华为对象存储
 **/

public class ImageUtil {

    private static final String accessKey = "WRTDRVZJBUXABJ7XOE7L";
    private static final String secretKey = "wmrCAHWU79RF46wpWhJuPnWFfflqxBIzHB4yxdm8";
    private static final String endPoint = "obs.cn-southwest-2.myhuaweicloud.com";
    private static final String bucketName = "bishe-bucket";

    public static void main(String[] args) throws IOException {
        MultipartFile file = getFile();
        String url = upload(file);
        System.out.println(url);
    }

    public static MultipartFile getFile() throws IOException {
        // 指定本地文件路径
        File file = new File("D:\\bishe\\mall\\mall-server\\file\\18.png");
        // 创建一个 FileInputStream
        FileInputStream input = new FileInputStream(file);
        // 创建 MockMultipartFile
        MockMultipartFile images = new MockMultipartFile("file", file.getName(),"image/jpeg" ,input);
        // 关闭输入流
        input.close();
        return images;
    }

    public static String upload(MultipartFile file) {

        try (ObsClient client = new ObsClient(accessKey, secretKey, endPoint)) {
            String fileExt = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf(".")+1);
            PutObjectRequest request = new PutObjectRequest();
            request.setInput(file.getInputStream());
            request.setBucketName(bucketName);
            request.setObjectKey("mall/" + System.currentTimeMillis() + "." + fileExt);
            PutObjectResult result = client.putObject(request);
            //https://bishe-bucket.obs.cn-southwest-2.myhuaweicloud.com:443/mall/1742196910183.png?AccessKeyId=HSTAKD74GH6G9HJLEGC4&Expires=1742197297&response-content-disposition=inline&response-content-type=application/octet-stream&versionId=null&x-obs-security-token=hQpjbi1zb3V0aC0xAQAAAz5IU1RBS0Q3NEdINkc5SEpMRUdDNLCJv2p9Xfi1BH_FIZ4gJrRkD49hR8fSsN24sExSOX4OAJ49zz7Ph8p_lDLIfO3bT6qEIq9M9z2itWzjMNZ3jknpaOcJyzaGQNs8qNZ0nRMD2q5vjp1NxEIdB7THVuOX64Ohyti5G_bwdolKJVSDGhB6fNCUCd4k0AChTM-0tlYNDAm7o47g11c-tVX8e-ftT5yzSots1KQrEHDexQSWB0cGsNRvsNRnU2VJFH0XSqlARlwWAEmYJp4hGOAqWT5D8tSeMzZN8D7QzwsmNbM2rI7UUhsTon5LPLoBbjpQRq1RNZN-nZMx1Cq-LhS-FThyM6Z7-DyjwnDKP2j570_yLZ9DjjUUvA9gmIjDjUx_LnMoeABPlpRcK2_VZ5Nam3HrJzadBIk8eqvyGJKtcwiKJplJIaRCxp0jcCm8G88HO8jELdzKhVLuLHPCphctKBzp67rLubb6682gpYD-HLuXXJmJsPoBqBhzOmDzbHm9kPiAP0X-jLylONMGUSXMFPWSJQLnHx8TmxpR&Signature=apwBha3P77ZebDq4adc1A4Lf15s%3D
            return result.getObjectUrl();
        }catch (Exception e) {
            System.out.println(e.getMessage());
        }
        //返回图片url
        return null;
    }
}
